﻿using System;
using System.Configuration;
using System.Net.Mail;
using System.Text;
using System.Web.Security;

namespace WebPages.Account
{
    public partial class UnlockAccount : System.Web.UI.Page
    {
        void SendConfirmationEmail(string userName, string emailAddress)
        {
            // Now lets create an email message
            var emailMessage = new StringBuilder();
            var header = Resources.Email.EmailHeader.Replace("{0}", "Your MyApp account has been unlocked");
            emailMessage.Append(header);
            emailMessage.Append(string.Format("Hello, {0}.<br /><br />Your MyApp account is now unlocked, <a href=\"http://www.MyApp.com/Account/Login.aspx\">click here</a> to sign in.", userName));
            var footer = String.Format(Resources.Email.EmailFooter, "This e-mail was sent because someone unlocked an account at <a href=\"http://www.MyApp.com\">www.MyApp.com</a> that is registered to your e-mail address.");
            emailMessage.Append(footer);

            var email = new MailMessage { From = new MailAddress(ConfigurationManager.AppSettings["fromEmail"]) };
            email.To.Add(new MailAddress(emailAddress));
            email.Subject = "Your MyApp account has been unlocked";
            email.Body = emailMessage.ToString();
            email.IsBodyHtml = true;

            // Send the email
            var client = new SmtpClient();
            client.Send(email);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            // Lets Activate the User
            var userId = new Guid();    // Initialized to avoid compiler error

            if (!String.IsNullOrEmpty(Request.Params["Id"]) && Guid.TryParse(Request.Params["Id"], out userId))
            {
                var user = Membership.GetUser(userId);

                // Activate the user
                if (user != null)
                {
                    if (!user.IsLockedOut) alreadyUnlocked.Visible = true;
                    else
                    {
                        user.UnlockUser();

                        success.Visible = true;

                        // Update the user
                        Membership.UpdateUser(user);

                        SendConfirmationEmail(user.UserName, user.Email);
                    }
                }
                else notFound.Visible = true;
            }
            else badConfirmationId.Visible = true;

        }
    }
}